<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="案例名称" prop="caName">
        <el-input
          v-model="queryParams.caName"
          placeholder="请输入案例名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否显示" prop="caShow">
        <el-select
          v-model="queryParams.caShow"
          @change="changeCode"
          placeholder="请选择是否显示"
        >
          <el-option label="显示" value="0"></el-option>
          <el-option label="隐藏" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['applet:brand:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="caseList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="index" label="序号" align="center" />
      <el-table-column label="产品类型" align="center" prop="caType">
        <template slot-scope="{ row }">
          {{ selectDictLabels(pr_list, String(row.caType)) }}
        </template>
      </el-table-column>
      <el-table-column label="产品品牌" align="center" prop="caBrand">
        <template slot-scope="{ row }">
          {{ selectDictLabels(listBrand, String(row.caBrand)) }}
        </template>
      </el-table-column>
      <el-table-column label="产品型号" align="center" prop="caSeries">
        <template slot-scope="{ row }">
          {{ selectDictLabels(cpxhList, String(row.caSeries)) }}
        </template>
      </el-table-column>
      <el-table-column label="案例名称" align="center" prop="caName" />
      <el-table-column label="图片" align="center" prop="caPic">
        <template slot-scope="{ row }">
          <img :src="getImage(row.caPic)" alt="" style="height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="内容图片" align="center" prop="caDetail">
        <template slot-scope="{ row }">
          <div style="display: flex; flex-wrap: wrap">
            <el-image
              v-for="(item, index) in row.caDetail"
              :key="index"
              :src="item"
              :preview-src-list="[item]"
              style="width: 100px; height: 100px"
            >
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否显示" align="center" prop="caShow" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['applet:brand:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['applet:brand:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品品牌对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <div class="flex">
          <!-- left -->
          <div class="flex1">
            <el-form-item label="案例名称" prop="caName">
              <el-input v-model="form.caName" placeholder="请输入案例名称" />
            </el-form-item>
            <el-form-item label="产品品牌" prop="caBrand">
              <el-select v-model="form.caBrand" placeholder="请选择">
                <el-option
                  v-for="item in listBrand"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value + ''"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="颜色" prop="caColour">
              <el-input v-model="form.caColour" placeholder="请输入颜色" />
            </el-form-item>
            <el-form-item label="是否显示" prop="caShow">
              <el-radio-group v-model="form.caShow">
                <el-radio :label="0">显示</el-radio>
                <el-radio :label="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="图片" prop="caPic">
              <el-upload
                class="avatar-uploader"
                :action="uploadFileUrl"
                :show-file-list="false"
                :headers="headers"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="image" :src="image" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </div>
          <!-- right -->
          <div class="flex1">
            <el-form-item label="产品类型" prop="caType">
              <el-select v-model="form.caType" placeholder="请选择">
                <el-option
                  v-for="dict in pr_list"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value + ''"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="产品型号" prop="caSeries">
              <el-select v-model="form.caSeries" placeholder="请选择">
                <el-option
                  v-for="item in cpxhList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value + ''"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="描述" prop="caDescribe">
              <el-input v-model="form.caDescribe" placeholder="请输入描述" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
            <el-form-item label="详情图" prop="caDetail">
              <el-upload
                class="avatar-uploader"
                list-type="picture-card"
                :action="uploadFileUrl"
                :limit="10"
                :file-list="fileList"
                :headers="headers"
                :on-success="handleAvatarSuccess1"
                :before-upload="beforeAvatarUpload"
                :on-remove="remove"
              >
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  getCaseList,
  addCase,
  getCaseById,
  updateCase,
  delCase,
} from "@/api/case";
import { listBrand } from "@/api/product/brand"; // 产品类型
import { listModel } from "@/api/product/model"; // 产品型号

export default {
  name: "brand",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品品牌表格数据
      caseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        caBrand: null,
        caName: null,
        caType: null,
        caShow: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      UrlServer: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      image: "",
      pr_list: [], //产品类型
      listBrand: [], // 产品品牌
      cpxhList: [], // 产品型号

      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      imageList: [],
    };
  },
  created() {
    this.getList();
    // 获取字典数据
    //产品类型
    this.getDicts("product_type").then((response) => {
      this.pr_list = response.data.map((item) => {
        return {
          label: item.dictLabel,
          value: item.dictCode,
        };
      });
    });
    // 产品品牌
    listBrand().then((res) => {
      this.listBrand = res.rows.map((res) => {
        return {
          label: res.brName,
          value: res.id,
        };
      });
    });
    // 产品型号
    listModel().then((res) => {
      this.cpxhList = res.rows.map((item) => {
        return {
          label: item.prModel,
          value: item.id,
        };
      });
    });
  },
  methods: {
    getImage(url) {
      return this.UrlServer + url;
    },
    getList() {
      this.loading = true;
      getCaseList(this.queryParams).then((response) => {
        response.rows.map((item) => {
          if (item.caDetail) {
            console.log(item.caDetail);
            item.caDetail = item.caDetail.split(",").map((map) => {
              return process.env.VUE_APP_BASE_API + map;
            });
            console.log(item.caDetail);
          } else {
            item.caDetail = "";
          }
          item.caShow = item.caShow === 1 ? "隐藏" : "显示";
        });

        this.caseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCaseById(id).then((response) => {
        this.form = response.data;
        this.image = this.UrlServer + this.form.caPic;
        this.imageList = this.form.caDetail.split(",");
        this.fileList = this.imageList.map((item) => {
          return {
            name: item,
            url: this.UrlServer + item,
          };
        });
        this.title = "修改";
        this.open = true;
      });
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.image = URL.createObjectURL(file.raw);
      this.form.caPic = res.fileName;
    },
    // 上传图片
    handleAvatarSuccess1(res, file) {
      this.imageList.push(res.fileName);
      this.fileList.push({
        name: file.name,
        url: this.UrlServer + res.fileName,
      });
    },
    // 删除图片
    remove(file, fileList) {
      let index = this.fileList.findIndex((item) => {
        return item.name === file.name;
      });
      this.fileList.splice(index, 1);
      let index1 = this.imageList.findIndex((item) => {
        return item === file.name;
      });
      this.imageList.splice(index1, 1);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 20MB!");
      }
      return isLt2M;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 选中修改
    changeCode() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加案例";
    },
    // 表单重置
    reset() {
      this.form = {
        caBrand: null,
        caName: null,
        caType: null,
        caShow: 0,
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            this.form.caDetail = this.imageList.toString();
            updateCase(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.caDetail = this.imageList.toString();
            addCase(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除图标编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCase(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "applet/icon/export",
        {
          ...this.queryParams,
        },
        `icon_${new Date().getTime()}.xlsx`
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
